package cn.kgc.advice;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import static cn.kgc.base.SystemConstant.TOTAL_TIME;


/**
 * @author YC
 */
@Aspect
@Component
@Slf4j
public class TimingAdvice {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) || @within(org.springframework.stereotype.Controller)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 目标类名
        String className = joinPoint.getTarget().getClass().getName();
        // 目标方法名
        String methodName = joinPoint.getSignature().getName();

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 执行目标方法
        Object target = joinPoint.proceed();
        stopWatch.stop();
        // 执行目标方法的执行时间
        double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
        if (totalTimeSeconds > TOTAL_TIME) {
            log.warn("方法执行时间过长，请优化！方法名：{}，执行时间：{}秒", className + ":" + methodName, totalTimeSeconds);
        }

        return target;
    }

}
